package com.bodacn.keypoint;


import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentB extends Fragment implements View.OnClickListener {
    public static final int msgFocusBarcode = 1001;
    public static final int msgGetImg = 1002;
    public static final int msgShowImage =1003;
    public static final int MSG_ERRMSG = 1004;
    public static final int MSG_SCANBARCODE = 9001;
    public static final int MSG_DETAIL = 9002;
    public static final int MSG_MEASURE=9003;
    public static final int MSG_PROCRESULT=9004;
    public static final int titleHeight=58;
    public static String TAG=FragmentB.class.getName();
    //用于将Activity中的参数传给Fragment
    private Map<String, Object> fragmentParams = new HashMap<String, Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    Toast curToast;
    String curLoginUserNo, curLoginUser, curServiceUrl = "",curServiceDir="",curDepartNo, curDepart, CPUID, PrBarcode = "";
    String curImageFileName="",curStyleID="";
    EditText edt_barcode;
    Button btn_find,btn_Query,btn_edit;
    ImageButton btn_editBarcode;
    TextView txt_HintInfo,txt_OrderNo,txt_StyleNo,txt_PO,txt_Color, txt_PartName,txt_Size,txt_PackNo,txt_StyleSort,txt_Number,txt_TodayCheckNum,txt_TodayRepairNum;
    String CurFormNo="";
    //Measure
    Button view_affirmBtn, view_clearBtn, view_submitBtn,view_cancelBtn;
    Button view_oneBtn, view_twoBtn, view_threeBtn, view_fourBtn, view_fiveBtn, view_sixBtn, view_sevenBtn, view_eightBtn, view_nineBtn, view_zeroBtn, view_delBtn, view_pointBtn,view_divBtn,view_spaceBtn;
    TextView view_partName, view_measure, view_commDiffer;
    ListView measureListView;
    EditText view_realMeasure;
    //Question
    EditText view_numEdit;
    Button view_clearQuestionBtn, view_incBtn, view_decBtn, view_resetBtn, view_submitQuestionBtn;
    TextView view_questionText;
    GridView girdQuestionMa, girdQuestionDe;
    //布局的获取,主要为点击打标识服务;
    ImagePointLayout imageLayout;
    ArrayList<PointPlace> points;
    LinearLayout bottomLinear;
    //其他变量
    JSONArray detailJSON, questionJSON,  itemTypeJSON, itemDetailJSON, measureJSON,procRstJSON;
    private ProgressDialog waitDialog = null;

    //切换的两个按键;
    Button btn_SwitchQuestion, btn_SwitchMeasure;
    int curProcPosition = -1;
    int curMeasurePostion = -1;
    //用于切换
    FrameLayout qcframelayout, qc_card_back, qc_card_front;
    private AnimatorSet mRightOutSet; // 右出动画
    private AnimatorSet mLeftInSet; // 左入动画
    private boolean mIsShowBack;
    LinearLayout linerCardFront, linerCardBack;

    //判断是否为数字，不然不转
    public static boolean isNumeric(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public FragmentB() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity = (MainActivity) getActivity();
        mainHandler = activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerB(new MainActivity.OnTransParamsListenerB() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams != null) {
                    try {
                        String paramComm = mParams.get("ParamComm").toString();
                        if (paramComm == "LoginParam") {
                            Log.d(TAG, "LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo = mParams.get("LoginUserNo").toString();
                            curLoginUser = mParams.get("LoginUser").toString();
                            curServiceUrl = mParams.get("ServiceUrl").toString();
                            curServiceDir= mParams.get("ServiceDir").toString();
                            curDepartNo = mParams.get("DepartNo").toString();
                            curDepart = mParams.get("Depart").toString();
                            CPUID = mParams.get("CPUID").toString();
                            Log.d(TAG, "LoginParam------------------>2");
                            //发消息置焦点
                            Message msg = new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            //判断是否需要刷新疵点数据
                            if (questionJSON == null) refreshDetailData();
                            else if (questionJSON.length() == 0) refreshDetailData();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    // 设置动画
    private void setAnimators() {
        mRightOutSet = (AnimatorSet) AnimatorInflater.loadAnimator(getActivity(), R.animator.anim_out);
        mLeftInSet = (AnimatorSet) AnimatorInflater.loadAnimator(getActivity(), R.animator.anim_in);
        // 设置点击事件
        mRightOutSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                qcframelayout.setClickable(false);
                //全部显示，进行切换;
                setBackCardCompontView(true, true);

            }
        });
        mLeftInSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                qcframelayout.setClickable(true);
                //转显不显示后面的控件，防止误按;
                setBackCardCompontView(mIsShowBack, false);
            }
        });
    }

    // 改变视角距离, 贴近屏幕
    private void setCameraDistance() {
        int distance = 16000;
        float scale = getResources().getDisplayMetrics().density * distance;
        qc_card_front.setCameraDistance(scale);
        qc_card_back.setCameraDistance(scale);
    }

    // 翻转卡片
    public void flipCard(View view) {
        hideIM(view);
        // 正面朝上
        if (!mIsShowBack) {
            mRightOutSet.setTarget(qc_card_front);
            mLeftInSet.setTarget(qc_card_back);
            mRightOutSet.start();
            mLeftInSet.start();
            mIsShowBack = true;
        } else { // 背面朝上
            mRightOutSet.setTarget(qc_card_back);
            mLeftInSet.setTarget(qc_card_front);
            mRightOutSet.start();
            mLeftInSet.start();
            mIsShowBack = false;
        }

    }

    //设置是否显示背面的控件，不然会误按;
    public void setBackCardCompontView(boolean isVisible, boolean isAllShow) {
        //全显
        if (isAllShow == true) {
            linerCardBack.setVisibility(View.VISIBLE);
            linerCardFront.setVisibility(View.VISIBLE);
        } else  //局显
        {
            if (isVisible == false) {
                linerCardBack.setVisibility(View.INVISIBLE);
                linerCardFront.setVisibility(View.VISIBLE);
            } else {
                linerCardBack.setVisibility(View.VISIBLE);
                linerCardFront.setVisibility(View.INVISIBLE);
            }
        }
    }



    //刷新缸布列表;
    private void getImage(final String paramStyleID,final String paramStyleNo,final String paramStyleSort)
    {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    ResultSet re = ToolUtil.OpenSQL("Exec KeyPoint_GetStylePNG @StyleID='" + paramStyleID + "',@StyleNo='" + paramStyleNo + "',@StyleSort='" + paramStyleSort + "'");
                    if (re != null) {
                        re.next();
                        //使用Blob对象接收数据库里的图片
                        if (re.findColumn("ImgResult") > -1) {
                            String ImgResult = re.getString("ImgResult");
                            if (ImgResult.equals("OK")) {
                                java.sql.Blob imgBlob = re.getBlob("ImgFile");
                                //获取Blob对象的二进制流;
                                InputStream imgInS = imgBlob.getBinaryStream();
                                //加载一个网络图片
                                Bitmap bitmap = BitmapFactory.decodeStream(imgInS);
                                //保存图片;
                                saveBitmap(bitmap, curImageFileName);
                                //发消息显示图片;
                                Message msg = new Message();
                                msg.what = msgShowImage;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                        }
                    }
                    re.getStatement().getConnection().close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(run).start();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_b, container, false);
        initView(root);
        System.out.println(this.getClass().getName() + "_onCreateView");
        return root;
    }

    private void initView(View view) {
        btn_edit=(Button)view.findViewById(R.id.btn_edit);
        btn_edit.setOnClickListener(this);
        bottomLinear=view.findViewById(R.id.bottomLinear);
        points=new ArrayList<>();
        //用于取相对位置
        imageLayout =view.findViewById(R.id.imageLayout);
        imageLayout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //删除CacheDir文件
                deleteFilesByDirectory(getActivity().getCacheDir());
                curToast.setText("缓存文件已被清空!");
                curToast.show();
                return false;
            }
        });
        imageLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float opstX=event.getRawX()-bottomLinear.getX();
                float opstY=event.getRawY()-bottomLinear.getY()-titleHeight;//减去标题高度58
                PointPlace pointPlace1 = new PointPlace();
                pointPlace1.width_scale=opstX/v.getWidth();
                pointPlace1.height_scale=opstY/v.getHeight();
                points.clear();
                points.add(pointPlace1);
                imageLayout.setPoints(points);
                System.out.println(pointPlace1.width_scale+"----"+pointPlace1.height_scale);
                return false;
            }
        });
        //界面控件;
        measureListView =  view.findViewById(R.id.measureListView);
        measureListView.setFocusable(false);
        measureListView.setFocusableInTouchMode(false);
        measureListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                measureListView.setSelector(R.color.rowSelect);//实木色;
                try {
                    curMeasurePostion = position;
                    if (measureJSON.getJSONObject(position).has("PartName") == true)
                        view_partName.setText(measureJSON.getJSONObject(position).getString("PartName"));
                    if (measureJSON.getJSONObject(position).has("Measure") == true)
                        view_measure.setText(measureJSON.getJSONObject(position).getString("Measure"));
                    if (measureJSON.getJSONObject(position).has("CommDiffer") == true)
                        view_commDiffer.setText(measureJSON.getJSONObject(position).getString("CommDiffer"));
                    if (measureJSON.getJSONObject(position).has("RealMeasure") == true)
                        view_realMeasure.setText(measureJSON.getJSONObject(position).getString("RealMeasure"));
                    view_realMeasure.selectAll();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //成衣尺寸相关
        view_partName = (TextView) view.findViewById(R.id.view_Place);
        view_measure = (TextView) view.findViewById(R.id.view_measure);
        view_commDiffer = (TextView) view.findViewById(R.id.view_commDiffer);
        view_realMeasure = (EditText) view.findViewById(R.id.view_realMeasure);
        view_affirmBtn = (Button) view.findViewById(R.id.view_affirmBtn);
        view_affirmBtn.setOnClickListener(this);
        view_clearBtn = (Button) view.findViewById(R.id.view_clearBtn);
        view_clearBtn.setOnClickListener(this);
        view_submitBtn = (Button) view.findViewById(R.id.view_submitBtn);
        view_submitBtn.setOnClickListener(this);
        view_cancelBtn = (Button) view.findViewById(R.id.view_cancelBtn);
        view_cancelBtn.setOnClickListener(this);
        view_oneBtn = (Button) view.findViewById(R.id.view_oneBtn);
        view_oneBtn.setOnClickListener(this);
        view_twoBtn = (Button) view.findViewById(R.id.view_twoBtn);
        view_twoBtn.setOnClickListener(this);
        view_threeBtn = (Button) view.findViewById(R.id.view_threeBtn);
        view_threeBtn.setOnClickListener(this);
        view_fourBtn = (Button) view.findViewById(R.id.view_fourBtn);
        view_fourBtn.setOnClickListener(this);
        view_fiveBtn = (Button) view.findViewById(R.id.view_fiveBtn);
        view_fiveBtn.setOnClickListener(this);
        view_sixBtn = (Button) view.findViewById(R.id.view_sixBtn);
        view_sixBtn.setOnClickListener(this);
        view_sevenBtn = (Button) view.findViewById(R.id.view_sevenBtn);
        view_sevenBtn.setOnClickListener(this);
        view_eightBtn = (Button) view.findViewById(R.id.view_eightBtn);
        view_eightBtn.setOnClickListener(this);
        view_nineBtn = (Button) view.findViewById(R.id.view_nineBtn);
        view_nineBtn.setOnClickListener(this);
        view_zeroBtn = (Button) view.findViewById(R.id.view_zeroBtn);
        view_zeroBtn.setOnClickListener(this);
        view_delBtn = (Button) view.findViewById(R.id.view_delBtn);
        view_delBtn.setOnClickListener(this);
        view_pointBtn = (Button) view.findViewById(R.id.view_pointBtn);
        view_pointBtn.setOnClickListener(this);
        view_divBtn= (Button) view.findViewById(R.id.view_divBtn);
        view_divBtn.setOnClickListener(this);
        view_spaceBtn= (Button) view.findViewById(R.id.view_spaceBtn);
        view_spaceBtn.setOnClickListener(this);
        //PackInfo
        btn_find=(Button)view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_Query=(Button)view.findViewById(R.id.btn_Query);
        btn_Query.setOnClickListener(this);
        btn_editBarcode=(ImageButton)view.findViewById(R.id.btn_editBarcode);
        btn_editBarcode.setOnClickListener(this);
        btn_editBarcode.setFocusable(false);
        btn_editBarcode.setFocusableInTouchMode(false);
        //界面Edit;
        edt_barcode=(EditText)view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        hideIM(v);
                        if (edt_barcode.getText().length()==0) {
                            curToast.setText(getString(R.string.PleaseInputBarcode));
                            curToast.show();
                        }
                        String CurPage;
                        //Question面和Measure面是不同的参数;
                        if (mIsShowBack == false) CurPage = "Question";
                        else CurPage = "Measure";
                        //执行查询;
                        playRingtone();
                        scanBarcodeData(edt_barcode.getText().toString(),CurFormNo,txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),CurPage,"");
                        //未有焦点
                        if (edt_barcode.isFocused()==false){
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        } else edt_barcode.selectAll();
                    }

                }
                return false;
            }
        });
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        txt_HintInfo=view.findViewById(R.id.txt_HintInfo);
        txt_OrderNo=view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo=view.findViewById(R.id.txt_StyleNo);
        txt_PO=view.findViewById(R.id.txt_PO);
        txt_Color=view.findViewById(R.id.txt_Color);
        txt_PartName =view.findViewById(R.id.txt_PartName);
        txt_Size=view.findViewById(R.id.txt_Size);
        txt_PackNo=view.findViewById(R.id.txt_PackNo);
        txt_StyleSort=view.findViewById(R.id.txt_StyleSort);
        txt_Number=view.findViewById(R.id.txt_Number);
        txt_TodayCheckNum=view.findViewById(R.id.txt_TodayCheckNum);
        txt_TodayRepairNum=view.findViewById(R.id.txt_TodayRepairNum);

        //切换界面
        btn_SwitchQuestion = view.findViewById(R.id.btn_SwitchQuestion);
        btn_SwitchQuestion.setOnClickListener(this);
        btn_SwitchMeasure = view.findViewById(R.id.btn_SwitchMeasure);
        btn_SwitchMeasure.setOnClickListener(this);
        //切换卡片;
        qcframelayout = view.findViewById(R.id.qcframelayout);
        qc_card_back = view.findViewById(R.id.qc_card_back);
        qc_card_front = view.findViewById(R.id.qc_card_front);
        linerCardFront = view.findViewById(R.id.linerCardFront);
        linerCardBack = view.findViewById(R.id.linerCardBack);

        //疵点界面相关
        view_questionText = view.findViewById(R.id.view_questionText);
        view_numEdit = view.findViewById(R.id.view_numEdit);
        view_incBtn = view.findViewById(R.id.view_incBtn);
        view_incBtn.setOnClickListener(this);
        view_decBtn = view.findViewById(R.id.view_decBtn);
        view_decBtn.setOnClickListener(this);
        view_resetBtn = view.findViewById(R.id.view_resetBtn);
        view_resetBtn.setOnClickListener(this);
        view_submitQuestionBtn = view.findViewById(R.id.view_submitQuestionBtn);
        view_submitQuestionBtn.setOnClickListener(this);
        view_clearQuestionBtn = view.findViewById(R.id.view_clearQuestionBtn);
        view_clearQuestionBtn.setOnClickListener(this);

        girdQuestionMa = view.findViewById(R.id.girdQuestionMa);
        girdQuestionMa.setFocusable(false);
        girdQuestionMa.setFocusableInTouchMode(false);
        girdQuestionMa.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                girdQuestionMa.setSelector(R.color.rowSelect);//实木色;
                String QuestionType = null;
                try {
                    QuestionType = itemTypeJSON.getJSONObject(position).getString("QuestionType");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sliptQuestionDeJson(QuestionType);
                //System.out.println(itemDetailJSON);
                final QuestionDeAdapter questionDeAdapter = new QuestionDeAdapter(getActivity());
                girdQuestionDe.setAdapter(questionDeAdapter);
            }
        });
        girdQuestionDe = view.findViewById(R.id.girdQuestionDe);
        girdQuestionDe.setFocusableInTouchMode(false);
        girdQuestionDe.setFocusable(false);
        girdQuestionDe.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView item_QuestionName = (TextView) view.findViewById(R.id.item_QuestionName);
                String tmpQuestion = view_questionText.getText().toString();
                if (tmpQuestion.length() > 0) {
                    if (tmpQuestion.indexOf(item_QuestionName.getText().toString()) == -1)
                        tmpQuestion = tmpQuestion + ',' + item_QuestionName.getText().toString();
                } else tmpQuestion = item_QuestionName.getText().toString();
                System.out.println(tmpQuestion);
                view_questionText.setText(tmpQuestion);
            }
        });
        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);
        //提示框pd=new ProgressDialog(this);
        waitDialog = new ProgressDialog(getActivity());
        waitDialog.setTitle(getString(R.string.SystemHint));
        //绑定动画;
        setAnimators(); // 设置动画
        setCameraDistance(); // 设置镜头距离
        mIsShowBack = true;//初始界面显正面刷卡,假设当前为反面;
        flipCard(qcframelayout);//先切换下动画
    }

    /**
     * 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理 * * @param directory
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }

    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }

    //根据卡号或条码刷新数据;
    private void scanBarcodeData(String BarcodeParam, String FormNoParam,String OrderNoParam, String StyleNoParam, String CurPageParam,String curNumber) {
        PrBarcode = BarcodeParam;
        try {
            detailJSON = new JSONArray("[]");
            points.clear();
            PointPlace pointPlace1 = new PointPlace();
            pointPlace1.width_scale=0;
            pointPlace1.height_scale=0;
            points.clear();
            points.add(pointPlace1);
            imageLayout.setPoints(points);
            //清除界面显示内容;
            clearFormText();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_CutCheckBarcode @Barcode='" + BarcodeParam + "',@FormNo='" + FormNoParam
                + "',@OrderNo='" + OrderNoParam + "',@StyleNo='" + StyleNoParam
                + "',@OPERTYPE='SCANBARCODE',@CurPage='" + CurPageParam + "',@EditNum='" + curNumber +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //根据条码及界面上显示的内容调用尺寸数据;
    private void refreshMeasureData(String BarcodeParam, String FormNoParam, String OrderNoParam, String StyleNoParam) {
        try {
            measureJSON = new JSONArray("[]");
            curMeasurePostion = -1;
            final MeasureListAdapter measureListAdapter = new MeasureListAdapter(getActivity());
            measureListView.setAdapter(measureListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_GetMeasure @Barcode='" + BarcodeParam
                + "',@FormNo='" + FormNoParam + "',@OrderNo='" + OrderNoParam + "',@StyleNo='" + StyleNoParam
                + "',@OPERTYPE='MEASURE',@Section='CUT',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    private void SaveQuestionData(String BarcodeParam, String FormNoParam, String OrderNoParam, String StyleNoParam, String QuestionParam, String NumberParam, String CurPageParam,Double WidthScaleParam,Double HeightScalearam) {
        System.out.println("SaveQuestionData");
        view_submitQuestionBtn.setEnabled(false);
        try {
            detailJSON = new JSONArray("[]");
            //清除界面显示内容;
            clearFormText();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        waitDialog.setTitle("保存数据到服务器.....");
        waitDialog.show();
        //执行SQL过程
        String SqlComm="Exec KeyPoint_CutCheckBarcode @Barcode='" + BarcodeParam
                + "',@FormNo='" + FormNoParam + "',@OrderNo='" + OrderNoParam + "',@StyleNo='" + StyleNoParam
                + "',@OPERTYPE='SCANBARCODE',@CurPage='" + CurPageParam + "',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "',@Question='" + QuestionParam + "',@Number='" + NumberParam
                + "',@WidthScale=" + String.valueOf(WidthScaleParam)+ ",@HeightScale=" + String.valueOf(HeightScalearam);
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    //获取疵点类型;
    private void refreshDetailData() {
        try {
            itemTypeJSON = new JSONArray("[]");
            //显示到orderListGrid中;
            final QuestionMaAdapter questionMaAdapter = new QuestionMaAdapter(getActivity());
            girdQuestionMa.setAdapter(questionMaAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_GetQuestionCode @OPERTYPE='DETAIL',@Section='CUT',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }



    //清除界面显示内容
    private void clearFormText() {
        /*

         */
    }

    //填充界面显示内容;
    private void fillFormtext(JSONArray paramJSON) {
        if (paramJSON.length() > 0) {
            try {
                System.out.println("1");
                if (paramJSON.getJSONObject(0).has("StyleID")==true) curStyleID=paramJSON.getJSONObject(0).getString("StyleID");
                if (paramJSON.getJSONObject(0).has("FormNo") == true) CurFormNo=paramJSON.getJSONObject(0).getString("FormNo");
                if (paramJSON.getJSONObject(0).has("OrderNo")==true) txt_OrderNo.setText(paramJSON.getJSONObject(0).getString("OrderNo"));
                if (paramJSON.getJSONObject(0).has("StyleNo")==true) txt_StyleNo.setText(paramJSON.getJSONObject(0).getString("StyleNo"));
                if (paramJSON.getJSONObject(0).has("PO")==true) txt_PO.setText(paramJSON.getJSONObject(0).getString("PO"));
                if (paramJSON.getJSONObject(0).has("Color")==true) txt_Color.setText(paramJSON.getJSONObject(0).getString("Color"));
                if (paramJSON.getJSONObject(0).has("PackNo")==true) txt_PackNo.setText(paramJSON.getJSONObject(0).getString("PackNo"));
                if (paramJSON.getJSONObject(0).has("Size")==true) txt_Size.setText(paramJSON.getJSONObject(0).getString("Size"));
                if (paramJSON.getJSONObject(0).has("StyleSort")==true) txt_StyleSort.setText(paramJSON.getJSONObject(0).getString("StyleSort"));
                if (paramJSON.getJSONObject(0).has("PartName")==true) txt_PartName.setText(paramJSON.getJSONObject(0).getString("PartName"));
                if (paramJSON.getJSONObject(0).has("Number")==true) txt_Number.setText(paramJSON.getJSONObject(0).getString("Number"));
                if (paramJSON.getJSONObject(0).has("HintInfo")==true) txt_HintInfo.setText(paramJSON.getJSONObject(0).getString("HintInfo"));
                if (paramJSON.getJSONObject(0).has("SizeType")==true) {
                    if (paramJSON.getJSONObject(0).getString("SizeType").toLowerCase().equals("decimal")==true){
                        view_pointBtn.setVisibility(View.VISIBLE);
                        view_delBtn.setVisibility(View.VISIBLE);
                        view_divBtn.setVisibility(View.GONE);
                        view_spaceBtn.setVisibility(View.GONE);
                    } else
                    {
                        view_pointBtn.setVisibility(View.GONE);
                        view_delBtn.setVisibility(View.GONE);
                        view_divBtn.setVisibility(View.VISIBLE);
                        view_spaceBtn.setVisibility(View.VISIBLE);
                    }
                }
                if (paramJSON.getJSONObject(0).has("TodayCheckNum")==true)
                    txt_TodayCheckNum.setText(paramJSON.getJSONObject(0).getString("TodayCheckNum"));
                if (paramJSON.getJSONObject(0).has("TodayRepairNum")==true)
                    txt_TodayRepairNum.setText(paramJSON.getJSONObject(0).getString("TodayRepairNum"));
                if (paramJSON.getJSONObject(0).has("BadNum") == true)
                    view_numEdit.setText(paramJSON.getJSONObject(0).getString("BadNum"));
                if (paramJSON.getJSONObject(0).has("Question") == true)
                    view_questionText.setText(paramJSON.getJSONObject(0).getString("Question"));
                if (paramJSON.getJSONObject(0).has("ErrInfo") == true) {
                    MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(), R.raw.warn);
                    mediaPlayer.start();
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle(getString(R.string.SystemHint)).setMessage(paramJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideBottomUIMenu();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
                if (paramJSON.getJSONObject(0).has("ResultInfo") == true) {
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle(getString(R.string.SystemHint)).setMessage(paramJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideBottomUIMenu();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
                if (paramJSON.getJSONObject(0).has("NeedMeasure") == true) {
                    if (paramJSON.getJSONObject(0).getString("NeedMeasure").toUpperCase().equals("YES") == true) {
                        System.out.println("NeedMeasure------------------------------->");
                        //获取尺寸;
                        refreshMeasureData(edt_barcode.getText().toString(), CurFormNo, txt_OrderNo.getText().toString(), txt_StyleNo.getText().toString());
                    }
                    if (paramJSON.getJSONObject(0).getString("NeedMeasure").toUpperCase().equals("CLEAR") == true) {
                        System.out.println("ClearMeasure------------------------------->");
                        //清除尺寸;
                        ClearMeasureValue();
                    }
                }
                if (paramJSON.getJSONObject(0).has("ImgFileName") == true){
                    curImageFileName =paramJSON.getJSONObject(0).getString("ImgFileName");
                    //判断本地是否有图片;
                    String imgfilepath = getActivity().getCacheDir().toString();
                    File file = new File(imgfilepath + "/" + curImageFileName);
                    System.out.println("图片文件路径:" + imgfilepath + "/" + curImageFileName);
                    //判断图片是否存在，如果不存在则从网络获取;
                    if (file.exists() == true) {
                        Log.d(TAG, "准备从本地取图片显示---------------");
                        //从本地取图片
                        Bitmap bitmap = getLoacalBitmap(imgfilepath + "/" + curImageFileName);
                        imageLayout.setImgBg(bitmap);
                    } else {
                        Log.d(TAG, "发消息从网络获取图片---------------");
                        Drawable drawable = getResources().getDrawable(R.mipmap.err404);
                        BitmapDrawable errBitDraw = (BitmapDrawable) drawable;
                        imageLayout.setImgBg(errBitDraw.getBitmap());
                        //发前消息，获取图片;
                        Message msg = new Message();
                        msg.what = msgGetImg;
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }



    /**
     * @param @param  url 本地路径
     * @param @return
     * @return Bitmap
     * @throws
     * @Title: getLoacalBitmap
     * @Description: 加载本地图片
     */
    public Bitmap getLoacalBitmap(String url) {
        if (url != null) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(url);
                return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fis = null;
                }
            }
        } else {
            return null;
        }
    }


    /**
     * 保存文件
     */
    public void saveBitmap(Bitmap bm, String fileName) {
        //获取MainActivity
        MainActivity activity = (MainActivity) getActivity();
        //String imgfilepath=activity.SaveFilePath+activity.SaveIMGFolder;
        String imgfilepath = activity.getCacheDir().toString();
        Log.d("saveBitmap", "imgfilepath:" + imgfilepath);
        File f = new File(imgfilepath, fileName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            if (fileName.toUpperCase().indexOf("PNG") > 0)
                bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            if ((fileName.toUpperCase().indexOf("JPG") > 0) || (fileName.toUpperCase().indexOf("JPEG") > 0))
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.i("saveBitmap", "已经保存成功");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }



    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }

    //设置焦点到扫描输入框
    private void setEditBarcodeFocus() {
        //设置焦点
        System.out.println(TAG+"设置焦点-------------------------------1.Start");
        if (edt_barcode != null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(getView());
            hideBottomUIMenu();
        }
        System.out.println(TAG+"设置焦点-------------------------------1.End");
    }

    @Override
    public void onStart() {
        super.onStart();
        setEditBarcodeFocus();
    }

    //修改包件数;
    private void showEditPakcNum(String paramNum ){
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("件数更改");
        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        View view = LayoutInflater.from(getContext()).inflate(R.layout.input_num, null);
        //    设置我们自己定义的布局文件作为弹出框的Content
        builder.setView(view);
        final EditText edt_oldNum =view.findViewById(R.id.edt_oldNum);
        edt_oldNum.setText(paramNum);
        final EditText edt_newNum = view.findViewById(R.id.edt_newNum);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                String a = edt_oldNum.getText().toString().trim();
                String b = edt_newNum.getText().toString().trim();
                if (b.length()>0) editPackNo(PrBarcode,b);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {

            }
        });
        builder.show();
    }

    //刷新缸布列表;
    private void editPackNo(String BarcodeParam,String NumberParam)
    {
        String CurPage;
        //Question面和Measure面是不同的参数;
        if (mIsShowBack == false) CurPage = "Question";
        else CurPage = "Measure";
        scanBarcodeData(BarcodeParam,CurFormNo,txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),CurPage,NumberParam);
    }
    @Override
    public void onClick(View v) {
        hideIM(v);
        hideBottomUIMenu();
        switch (v.getId()) {
            case R.id.btn_edit:
                if (txt_Number.getText().toString().length()>0) showEditPakcNum(txt_Number.getText().toString());
                else {
                    curToast.setText("请先扫描包条码!");
                    curToast.show();
                }
                break;
            case R.id.btn_Query:
                Intent intentQueryActivity=new Intent(getContext(),QueryActivity.class);
                Bundle paramBundle = new Bundle();
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("CPUID",CPUID);
                paramBundle.putString("QueryTitle", "裁床验片查询");
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                intentQueryActivity.putExtras(paramBundle);
                startActivity(intentQueryActivity);
                break;
            case R.id.btn_editBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;

            case R.id.btn_SwitchMeasure:
                flipCard(qcframelayout);
                break;
            case R.id.btn_SwitchQuestion:
                flipCard(qcframelayout);
                break;
            case R.id.view_incBtn:
                editNumInc(1);
                break;
            case R.id.view_decBtn:
                editNumInc(-1);
                break;
            case R.id.view_clearQuestionBtn:
                view_questionText.setText("");
                break;
            case R.id.view_resetBtn:
                view_numEdit.setText("1");
                break;
            case R.id.view_submitQuestionBtn:
                if (view_numEdit.getText().length() == 0) {
                    curToast.setText(getString(R.string.WarnHintNumber));
                    curToast.show();
                    return;
                }
                if (view_questionText.getText().length() == 0) {
                    curToast.setText(getString(R.string.WarnHintQuestion));
                    curToast.show();
                    return;
                }
                /*
                if ((points==null)||(points.size()<1)){
                    curToast.setText(getString(R.string.WarnHintQuestionPoint));
                    curToast.show();
                    return;
                }*/
                SaveQuestionData(PrBarcode, CurFormNo, txt_OrderNo.getText().toString(), txt_StyleNo.getText().toString(), view_questionText.getText().toString(), view_numEdit.getText().toString(), "Question",points.get(0).width_scale,points.get(0).height_scale);
                break;
            case R.id.view_oneBtn:
            case R.id.view_twoBtn:
            case R.id.view_threeBtn:
            case R.id.view_fourBtn:
            case R.id.view_fiveBtn:
            case R.id.view_sixBtn:
            case R.id.view_sevenBtn:
            case R.id.view_eightBtn:
            case R.id.view_nineBtn:
            case R.id.view_zeroBtn:
                Button tmpBtn1 = (Button) v.findViewById(v.getId());
                view_realMeasure.getText().append(tmpBtn1.getText());
                break;
            case R.id.view_delBtn:
                if (view_realMeasure.getText().length() > 0) {
                    view_realMeasure.setSelection(view_realMeasure.getText().length());
                    int start = view_realMeasure.getSelectionStart();
                    view_realMeasure.getText().delete(start - 1, start);
                }
                break;
            case R.id.view_pointBtn:
                System.out.println("indexOf:" + view_realMeasure.getText().toString().indexOf("."));
                if ((view_realMeasure.getText().toString().indexOf(".") == -1)&&(view_realMeasure.getText().toString().indexOf("/") == -1))  {
                    view_realMeasure.getText().append(".");
                }
                break;
            case R.id.view_divBtn:
                System.out.println("BindexOf:" + view_realMeasure.getText().toString().indexOf("/"));
                if ((view_realMeasure.getText().toString().indexOf(".") == -1)&&(view_realMeasure.getText().toString().indexOf("/") == -1)) {
                    view_realMeasure.getText().append("/");
                }
                break;
            case R.id.view_spaceBtn:
                System.out.println("BindexOf:" + view_realMeasure.getText().toString().indexOf(" "));
                if (view_realMeasure.getText().toString().indexOf(" ") == -1) {
                    view_realMeasure.getText().append(" ");
                }
                break;
            case R.id.view_clearBtn:
                view_realMeasure.setText("");
                break;
            case R.id.view_affirmBtn:

                if ((view_realMeasure.getText().length() > 0)&&(curMeasurePostion>-1)&&(measureJSON!=null)){
                    try {
                        //判断值是否超过公差;
                        String ConColor = "";
                        String differValue ="";
                        JSONObject tmpJSON = CheckMeasureDiffer(view_realMeasure.getText().toString(), view_measure.getText().toString(), view_commDiffer.getText().toString());
                        try {
                            ConColor = tmpJSON.getString("ConColor");
                            differValue = tmpJSON.getString("DifferValue");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        measureJSON.optJSONObject(curMeasurePostion).put("ConColor", ConColor);
                        measureJSON.optJSONObject(curMeasurePostion).put("RealMeasure", view_realMeasure.getText().toString());
                        measureJSON.optJSONObject(curMeasurePostion).put("DifferValue", differValue);
                        //更新修改过的行;
                        ((BaseAdapter) measureListView.getAdapter()).notifyDataSetChanged();
                        //只更新修改过的值;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    curToast.setText("请输入实际尺寸！");
                    curToast.show();
                }
                break;
            case R.id.view_submitBtn:
                putMeasureList(edt_barcode.getText().toString(), CurFormNo, txt_OrderNo.getText().toString(), txt_StyleNo.getText().toString());
                break;
            case R.id.view_cancelBtn:
                ClearMeasureValue();
            default:
                break;
        }

    }

    //分数字符串转小数
    private String transTotoDecimal(String paramString){
        String resultString="0",zsStr="0",fzStr="",fmStr="";
        if (paramString.indexOf(" ")>-1) {
            zsStr=paramString.substring(0,paramString.indexOf(" "));
            paramString=paramString.substring(paramString.indexOf(" ")+1);
        }
        else zsStr="0";
        if (paramString.indexOf("/")>-1){
            fzStr=paramString.substring(0,paramString.indexOf("/"));
            fmStr=paramString.substring(paramString.indexOf("/")+1);
        }
        if ((fzStr.length()==0)||(fmStr.length()==0)) return zsStr;
        float rtnValue=0;
        System.out.println("zsstr:"+zsStr+" fzStr:"+fzStr+" fmstr:"+fmStr);
        //转为小数值
        if (isNumeric(fzStr)&&isNumeric(fmStr)) rtnValue=(Float.parseFloat(zsStr)*Float.parseFloat(fmStr)+Float.parseFloat(fzStr))/(Float.parseFloat(fmStr));
        resultString=String.valueOf((double)Math.round(rtnValue*1000)/1000);
        return resultString;
    }

    //小数转分数
    public static String xs2fs(double fNumber) {
        //格式化为3位小数;
        DecimalFormat df = new DecimalFormat();
        df.setMaximumFractionDigits(3);
        String sA = df.format(fNumber);
        if (sA.indexOf(".") < 0) {
            // fNumber is an integer
            return sA;
        }
        String sZsbf = sA.substring(0,sA.indexOf(".") );
        String sXsbf = sA.substring(sA.indexOf(".") + 1);
        int nXsws = sXsbf.length() ; //小数位数
        long lFenmu = 1;
        for (int k=0; k< nXsws; k++) lFenmu *= 10;
        long lFenzi = Long.parseLong( sZsbf + sXsbf );
        long lXs = (lFenzi < lFenmu) ? lFenzi : lFenmu;
        System.out.println(lXs);
        long j ;//最大公约数
        for (j = lXs; j > 1; j --) {
            if (lFenzi % j ==0 && lFenmu % j == 0) {
                break;
            }
        }
        lFenzi = lFenzi / j;
        lFenmu = lFenmu / j;
        long zs= lFenzi / lFenmu;
        lFenzi=lFenzi % lFenmu;
        return String.valueOf(zs+" "+lFenzi) + "/" + String.valueOf(lFenmu) ;

    }

    //用于检查值是否超出范围
    private JSONObject CheckMeasureDiffer(String paramRealMeasure, String paramMeasure, String paramCommDiffer) {
        String maxStr, minStr;
        double differValue;
        String ConColor;
        JSONObject resultJSON;
        if (paramCommDiffer.indexOf(",") > -1) {
            maxStr = paramCommDiffer.substring(0, paramCommDiffer.indexOf(","));
            minStr = paramCommDiffer.substring(paramCommDiffer.indexOf(",") + 1);
        } else {
            if (paramCommDiffer.indexOf("±") > -1) {
                maxStr = paramCommDiffer.substring(paramCommDiffer.indexOf("±") + 1);
            } else {
                maxStr = paramCommDiffer;
            }
            if (maxStr.indexOf("/")>-1){
                maxStr=transTotoDecimal(maxStr);
            }
            minStr = "-" + maxStr;
        }
        if (paramRealMeasure.indexOf("/")>-1){
            paramRealMeasure=transTotoDecimal(paramRealMeasure);
        }
        if (paramMeasure.indexOf("/")>-1){
            paramMeasure=transTotoDecimal(paramMeasure);
        }
        System.out.println("maxStr:" + maxStr + " minStr:" + minStr +" paramMeasure:"+paramMeasure+" paramRealMeasure:"+paramRealMeasure+" paramCommDiffer:"+paramCommDiffer);
        differValue = 0;
        ConColor = "0";
        if ((isNumeric(paramRealMeasure) == true) && (isNumeric(paramMeasure) == true)) {
            differValue = Float.parseFloat(paramRealMeasure) - Float.parseFloat(paramMeasure);
            if ((differValue > Float.parseFloat(maxStr)) || (differValue < Float.parseFloat(minStr)))
                ConColor = "2";
            else ConColor = "1";
        }
        //差值判断否需要转成分数
        if (view_divBtn.getVisibility()==View.VISIBLE)
        {
            //格式化为1位小数;
            DecimalFormat df = new DecimalFormat();
            df.setMaximumFractionDigits(3);
            String differValueStr = df.format(differValue);
            if (differValue<0) differValueStr=differValueStr.replace("-","");
            System.out.println("A-differValueStr:"+differValueStr);
            differValueStr=xs2fs(Math.abs(differValue));
            if (differValue<0) differValueStr="-"+differValueStr;
            System.out.println("B-differValueStr:"+differValueStr);
            resultJSON = new JSONObject();
            try {
                resultJSON.put("ConColor", ConColor);
                resultJSON.put("DifferValue", differValueStr);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else
            {
            //格式化为1位小数;
            DecimalFormat df = new DecimalFormat();
            df.setMaximumFractionDigits(1);
            String differValueStr = df.format(differValue);
            resultJSON = new JSONObject();
            try {
                resultJSON.put("ConColor", ConColor);
                resultJSON.put("DifferValue", differValueStr);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return resultJSON;
    }

    //view_editNum 增加;
    private void editNumInc(int i) {
        if (isNumeric(view_numEdit.getText().toString()) == true) {
            if (view_numEdit.getText().toString().length() == 0) view_numEdit.setText("1");
            else
                view_numEdit.setText(String.valueOf(Integer.parseInt(view_numEdit.getText().toString()) + i));
            if (Integer.parseInt(view_numEdit.getText().toString()) < 1) view_numEdit.setText("1");
        } else view_numEdit.setText("1");
    }

    //提交所选择的工序至服务器,然后刷新工序列表;
    private void putMeasureList(final String paramBarcode,final String paramFormNo,final String paramOrderNo,final String paramStyleNo) {
        if (measureJSON == null) return;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String SqlComm;
                String tmpMeasureID = java.util.UUID.randomUUID().toString();
                //将数据读到JSONArray;
                try {
                    PreparedStatement pstmt = ToolUtil.getSQLConnection().prepareStatement(
                            "Insert into SceneMeasureDe(MeasureDeID,MeasureMaID,PartName,Measure,CommDiffer,RealMeasure,DifferValue) values(newid(),?,?,?,?,?,?)");
                    //增加明细表
                    for (int i = 0; i < measureJSON.length(); i++) {
                        if (measureJSON.getJSONObject(i).has("RealMeasure") == true) {
                            if (measureJSON.getJSONObject(i).getString("RealMeasure").length() > 0) {
                                pstmt.setString(1, tmpMeasureID);
                                pstmt.setString(2, measureJSON.getJSONObject(i).getString("PartName"));
                                pstmt.setString(3, measureJSON.getJSONObject(i).getString("Measure"));
                                pstmt.setString(4, measureJSON.getJSONObject(i).getString("CommDiffer"));
                                pstmt.setString(5, measureJSON.getJSONObject(i).getString("RealMeasure"));
                                pstmt.setString(6, measureJSON.getJSONObject(i).getString("DifferValue"));
                                pstmt.executeUpdate();
                            }
                        }
                    }
                    pstmt.close();
                    //增加主表;
                    pstmt = ToolUtil.getSQLConnection().prepareStatement(
                            "Insert into SceneMeasureMa(MeasureMaID,Barcode,FormNo,OrderNo,StyleNO,UserNo,UserName,CPUID,CreateTime) values(?,?,?,?,?,?,?,?,getdate())");
                    pstmt.setString(1, tmpMeasureID);
                    pstmt.setString(2, paramBarcode);
                    pstmt.setString(3, paramFormNo);
                    pstmt.setString(4, paramOrderNo);
                    pstmt.setString(5, paramStyleNo);
                    pstmt.setString(6, curLoginUserNo);
                    pstmt.setString(7, curLoginUser);
                    pstmt.setString(8, CPUID);
                    pstmt.executeUpdate();
                    pstmt.close();
                    //调用存储过程;
                    SqlComm = " Exec ScenePAD_TransMeasure @MeasureMaID='" + tmpMeasureID + "'";
                    ReadSQLData(SqlComm);
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        };
        new Thread(run).start();
    }
    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null) {
                //任意消息来均置焦点
                if (edt_barcode.isFocused()==false) setEditBarcodeFocus();
                else edt_barcode.selectAll();
                if (waitDialog.isShowing()==true) waitDialog.cancel();
                if (view_submitQuestionBtn.isEnabled()==false) view_submitQuestionBtn.setEnabled(true);
                //消息处理;
                System.out.println("收到的消息是："+msg.what);
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_ERRMSG:
                        Bundle bundle=msg.getData();
                        curToast.setText(bundle.getString("MSG"));
                        curToast.show();
                        break;
                    case msgGetImg:
                        //设置焦点
                        System.out.println(TAG+"获取图片-------------------------------1.Start");
                        if (curImageFileName.length()>0)
                            getImage(curStyleID,txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                        System.out.println(TAG+"获取图片-------------------------------1.End");
                        break;
                    case msgShowImage:
                        //判断本地是否有图片;
                        String imgfilepath = getActivity().getCacheDir().toString();
                        File file = new File(imgfilepath + "/" + curImageFileName);
                        //判断图片是否存在，如果不存在则从网络获取;
                        if (file.exists() == true) {
                            Log.d(TAG, "准备从本地取图片显示---------------");
                            //从本地取图片
                            Bitmap bitmap = getLoacalBitmap(imgfilepath + "/" + curImageFileName);
                            imageLayout.setImgBg(bitmap);
                        }
                        break;
                    case MSG_SCANBARCODE:
                        fillFormtext(detailJSON);
                        break;
                    case MSG_DETAIL:
                        //分解JSON
                        sliptQuestionJson();
                        break;
                    case MSG_MEASURE:
                        //显示预排单;
                        final MeasureListAdapter measureListAdapter = new MeasureListAdapter(getActivity());
                        if (measureListView != null)
                            measureListView.setAdapter(measureListAdapter);
                        if (measureJSON.length()>0){
                            curMeasurePostion=0;
                            measureListView.setSelection(0);
                            try {
                                if (measureJSON.getJSONObject(curMeasurePostion).has("PartName") == true)
                                    view_partName.setText(measureJSON.getJSONObject(curMeasurePostion).getString("PartName"));
                            if (measureJSON.getJSONObject(curMeasurePostion).has("Measure") == true)
                                view_measure.setText(measureJSON.getJSONObject(curMeasurePostion).getString("Measure"));
                            if (measureJSON.getJSONObject(curMeasurePostion).has("CommDiffer") == true)
                                view_commDiffer.setText(measureJSON.getJSONObject(curMeasurePostion).getString("CommDiffer"));
                            if (measureJSON.getJSONObject(curMeasurePostion).has("RealMeasure") == true)
                                view_realMeasure.setText(measureJSON.getJSONObject(curMeasurePostion).getString("RealMeasure"));
                            view_realMeasure.selectAll();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        break;

                    case MSG_PROCRESULT:
                        String resultMsg = null;
                        try {
                            resultMsg = procRstJSON.optJSONObject(0).getString("PROCRESULT");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        //提示提交完成，需确认;
                        // 创建对话框
                        AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                .setTitle(getString(R.string.SystemHint)).setMessage(resultMsg)
                                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        hideBottomUIMenu();
                                    }
                                }).create();
                        alertDialog.show(); // 显示对话框
                        break;
                    default:
                        break;
                }
            }
        }
    };
    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = ToolUtil.QuerySQL2JSON(SQLComm);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OPERTYPE") == true) {
                            System.out.println("OPERTYPE:" + jsonArray.optJSONObject(0).getString("OPERTYPE"));
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("SCANBARCODE")) {
                                detailJSON = jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_SCANBARCODE;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            //疵点类别分解及显示
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("DETAIL")) {
                                questionJSON = jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_DETAIL;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);

                            }
                            //获取尺寸数据
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("MEASURE")) {
                                System.out.println("获取到成衣尺寸数据");
                                measureJSON = jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_MEASURE;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);

                            }
                        }
                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                        if (jsonArray.optJSONObject(0).has("PROCRESULT") == true) {
                            procRstJSON=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_PROCRESULT;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        new Thread(run).start();
    }


    //清空成衣尺寸填的值;
    private void ClearMeasureValue() {
        if (measureJSON != null)
            for (int i = 0; i < measureJSON.length(); i++) {
                try {
                    if (measureJSON.getJSONObject(i).has("RealMeasure") == true)
                        measureJSON.getJSONObject(i).put("RealMeasure", "");
                    if (measureJSON.getJSONObject(i).has("DifferValue") == true)
                        measureJSON.getJSONObject(i).put("DifferValue", "");
                    if (measureJSON.getJSONObject(i).has("ConColor") == true)
                        measureJSON.getJSONObject(i).put("ConColor", "0");
                    ((BaseAdapter) measureListView.getAdapter()).notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

    }

    //将取过来的问题代码分解类别和明细
    private void sliptQuestionJson() {
        String QuestionType = "";
        boolean needAdd = false;
        try {
            itemTypeJSON = new JSONArray("[]");
            if (questionJSON != null)
                for (int i = 0; i < questionJSON.length(); i++) {
                    needAdd = true;
                    if (questionJSON.optJSONObject(i).has("QuestionType") == true) {
                        System.out.println("sliptQuestionJsonA:" + questionJSON.optJSONObject(i).getString("QuestionType"));
                        for (int j = 0; j < itemTypeJSON.length(); j++) {
                            if (itemTypeJSON.optJSONObject(j).has("QuestionType") == true)
                                if (itemTypeJSON.optJSONObject(j).getString("QuestionType").equals(questionJSON.optJSONObject(i).getString("QuestionType"))) {
                                    needAdd = false;
                                    break;
                                }
                        }
                        System.out.println("sliptQuestionJsonB:" + questionJSON.optJSONObject(i).getString("QuestionType"));
                        if (needAdd == true) {
                            System.out.println("sliptQuestionJsonC:" + questionJSON.optJSONObject(i).getString("QuestionType"));
                            if (QuestionType.length() == 0)
                                QuestionType = questionJSON.optJSONObject(i).getString("QuestionType");
                            JSONObject selItemJSON = new JSONObject();
                            selItemJSON.put("QuestionType", questionJSON.optJSONObject(i).getString("QuestionType"));
                            itemTypeJSON.put(selItemJSON);
                        }
                    }
                }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        //取类型对应的明细;
        //System.out.println(itemTypeJSON);
        //显示QC疵点类型及明细;
        final QuestionMaAdapter questionMaAdapter = new QuestionMaAdapter(getActivity());
        girdQuestionMa.setAdapter(questionMaAdapter);
        sliptQuestionDeJson(QuestionType);
        //System.out.println(itemDetailJSON);
        final QuestionDeAdapter questionDeAdapter = new QuestionDeAdapter(getActivity());
        girdQuestionDe.setAdapter(questionDeAdapter);
    }


    //取疵点明细
    private void sliptQuestionDeJson(String paramQuestionType) {
        try {
            itemDetailJSON = new JSONArray("[]");
            if (questionJSON != null)
                for (int i = 0; i < questionJSON.length(); i++) {
                    if (questionJSON.optJSONObject(i).has("QuestionType") == true) {
                        if (questionJSON.optJSONObject(i).getString("QuestionType").equals(paramQuestionType) == true) {
                            if (questionJSON.optJSONObject(i).has("QuestionName")&&questionJSON.optJSONObject(i).has("QuestionCode")) {
                                JSONObject selItemJSON = new JSONObject();
                                selItemJSON.put("QuestionCode", questionJSON.optJSONObject(i).getString("QuestionCode"));
                                selItemJSON.put("QuestionName", questionJSON.optJSONObject(i).getString("QuestionName"));
                                itemDetailJSON.put(selItemJSON);
                            }
                        }
                    }
                }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    //订单表格适配器;
    public final class QuestionMaAdapter extends BaseAdapter {
        private LayoutInflater inflater;

        public QuestionMaAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return itemTypeJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return itemTypeJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null)
                convertView = inflater.inflate(R.layout.fragment_b_itemtype, null, false);
            //int pullVatListWidth=parent.getWidth();
            //convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(38)));
            int color = getResources().getColor(R.color.black);
            String tmpValue;
            try {
                Log.d("msg", "getView()----------------------------------------------------->" + position);
                TextView tv = (TextView) convertView.findViewById(R.id.item_PartName);// 显示文字
                if (itemTypeJSON.optJSONObject(position).has("QuestionType") == true)
                    tv.setText(itemTypeJSON.optJSONObject(position).get("QuestionType").toString());
                tv.setTextColor(color);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg", "QuestionMaAdapter_position:" + position);
            return convertView;
        }
    }

    //订单表格适配器;
    public final class QuestionDeAdapter extends BaseAdapter {
        private LayoutInflater inflater;

        public QuestionDeAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return itemDetailJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return itemDetailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null)
                convertView = inflater.inflate(R.layout.fragment_b_item, null, false);
            //int pullVatListWidth=parent.getWidth();
            //convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(38)));
            int color = getResources().getColor(R.color.black);
            String tmpValue;
            try {
                Log.d("msg", "getView()----------------------------------------------------->" + position);
                TextView tv = (TextView) convertView.findViewById(R.id.item_QuestionNo);// 显示文字
                if (itemDetailJSON.optJSONObject(position).has("QuestionCode") == true)
                    tv.setText(itemDetailJSON.optJSONObject(position).get("QuestionCode").toString());
                tv = (TextView) convertView.findViewById(R.id.item_QuestionName);// 显示文字
                if (itemDetailJSON.optJSONObject(position).has("QuestionName") == true)
                    tv.setText(itemDetailJSON.optJSONObject(position).get("QuestionName").toString());
                tv.setTextColor(color);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg", "QuestionDeAdapter_position:" + position);
            return convertView;
        }
    }

    //订单表格适配器;
    public final class MeasureListAdapter extends BaseAdapter {
        private LayoutInflater inflater;

        public MeasureListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return measureJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return measureJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null)
                convertView = inflater.inflate(R.layout.fragment_b_qcpagea_listhead, null, false);
            int pullVatListWidth = parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int) pullVatListWidth, (int) (42)));
            int color = getResources().getColor(R.color.transparent);
            String tmpValue;
            int textColor = getResources().getColor(R.color.text_black);
            try {
                Log.d("msg", "getView()----------------------------------------------------->" + position);
                if (measureJSON.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = measureJSON.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                }
                TextView tv = convertView.findViewById(R.id.txt_item_partName);
                if (measureJSON.optJSONObject(position).has("PartName") == true)
                    tv.setText(measureJSON.optJSONObject(position).getString("PartName").toString());
                tv.setTextColor(textColor);
                tv = convertView.findViewById(R.id.txt_item_measure);
                if (measureJSON.optJSONObject(position).has("Measure") == true)
                    tv.setText(measureJSON.optJSONObject(position).getString("Measure").toString());
                tv.setTextColor(textColor);
                tv = convertView.findViewById(R.id.txt_item_commDiffer);
                if (measureJSON.optJSONObject(position).has("CommDiffer") == true)
                    tv.setText(measureJSON.optJSONObject(position).getString("CommDiffer").toString());
                tv.setTextColor(textColor);
                tv = convertView.findViewById(R.id.txt_item_realMeasure);
                if (measureJSON.optJSONObject(position).has("RealMeasure") == true)
                    tv.setText(measureJSON.optJSONObject(position).getString("RealMeasure").toString());
                tv.setTextColor(textColor);
                tv = convertView.findViewById(R.id.txt_item_differValue);
                if (measureJSON.optJSONObject(position).has("DifferValue") == true)
                    tv.setText(measureJSON.optJSONObject(position).getString("DifferValue").toString());
                tv.setTextColor(textColor);
                tv.setBackgroundColor(color);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg", "MeasureListAdapter_position:" + position);
            return convertView;
        }
    }

}